<?php

class CategoryController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		$categories = Category::paginate(10);
		return View::make('category.index')->with(array('categories' => $categories));
	}


	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		$category = new Category;
		$categoryParent = new Category;
		return View::make('category.edit')->with(array('category' => $category, 'categoryParent' => $categoryParent, 'method' => 'post'));
	}


	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
			
		// Get all the inputs	
        $userdata = array(
            'name' => Input::get('name'),
            'parent_name' => Input::get('parent_name')
        );
        // Declare the rules for the form validation.
        $rules = array(
            'name'  => 'Required|unique:category,name',
            'parent_name'  => 'required_if:parent_name,/|exists:category,name'
        );

        // Validate the inputs.
        $validator = Validator::make($userdata, $rules);

        // Check if the form validates with success.
        if ($validator->passes()) {
			
			$category = new Category;
			$category->name = $userdata['name'];
			
			if ($userdata['parent_name'] == '/') {
				$categoryParent = Category::where('parent_id', '=', '0')->first();
				$category->parent_id = $categoryParent->id;
			} else {
				// Retrieve new category parent
				$categoryParent = Category::where('name', '=', $userdata['parent_name'])->first();
				$category->parent_id = $categoryParent->id;
			}
			
			if ($category->save())
			{
                // Redirect to homepage
                return Redirect::to('category')->with('success', 'Category successfully Updated');
            }
			else
			{
				// Redirect to the login page.
                return Redirect::to('category.edit')->withErrors(array('message' => 'Opps something wrong!!'));
			}
		}
		
        // Something went wrong.
        return Redirect::to('category/edit')->with(array('category' => $category, 'method' => 'post'))
										 ->withErrors($validator);
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		$category = Category::findOrFail($id);
		return View::make('category.show')->with('category', $category);
	}


	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		$category = Category::findOrFail($id);
		if ($category->parent_id === 0)
			$categoryParent = new Category;
		else
			$categoryParent = Category::find($category->parent_id);
		
		return View::make('category.edit')->with(array('category' => $category, 'categoryParent' => $categoryParent, 'method' => 'put'));
	}


	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		
		// Retrieve current category
		$category = Category::find($id);
			
		// Get all the inputs
        $userdata = array(
            'name' => Input::get('name'),
            'parent_name' => Input::get('parent_name')
        );

        // Declare the rules for the form validation.
        $rules = array(
            'name'  => 'Required',
            'parent_name'  => 'required_if:parent_name,/|exists:category,name'
        );

        // Validate the inputs.
        $validator = Validator::make($userdata, $rules);

        // Check if the form validates with success.
        if ($validator->passes()) {
			
			$category->name = $userdata['name'];
			
			if ($userdata['parent_name'] == '/') {
				$categoryParent = Category::where('parent_id', '=', '0')->first();
				$category->parent_id = $categoryParent->id;
			} else {
				// Retrieve new category parent
				$categoryParent = Category::where('name', '=', $userdata['parent_name'])->first();
				$category->parent_id = $categoryParent->id;
			}
			
			if ($category->save())
			{
                // Redirect to homepage
                return Redirect::to('category')->with('success', 'Category successfully Updated ');
            }
			else
			{
				// Redirect to the login page.
                return Redirect::to('category.edit')->withErrors(array('message' => 'Opps something wrong!!'));
			}
		}
		
        // Something went wrong.
        return Redirect::to('category/'.$category->id.'/edit')->with(array('category' => $category, 'method' => 'put'))
										 ->withErrors($validator);
	}
	
	/**
	 * Show the form for delete the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function delete($id)
	{
		$category = Category::find($id);
		return View::make('category.edit')->with(array('category' => $category, 'method' => 'delete'));
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$category = Category::find($id);
		
		CategoryController::deleteCategory($category->id);
		
		$category->delete();
		
		return Redirect::to('category')->with('success', 'Successfully deleted department!');
	}
	
	private function deleteCategory($id)
	{
		$categories = Category::where('parent_id', '=', $id)->get();
		foreach ($categories as $category) {
			Log::info('remove ' . $category->id);
			$category->delete();
			CategoryController::deleteCategory($category->id);
		}
		
	}
}
